#include "Editor.hpp"
#include "Engine.hpp"
#include "Components.hpp"
#include "Resources.hpp"
#include "imgui_impl_sdl2.h"
#include "imgui_impl_sdlrenderer2.h"
#include <algorithm>
#include <string>
#include <iostream>
#include "ScriptManager.hpp"

Editor::Editor(Engine* engine) : engine(engine) {
    // 初始化组件创建器映射
    componentCreators["Position"] = [this](entt::entity entity) {
        getRegistry().emplace<Position>(entity, 0.0f, 0.0f);
    };
    
    componentCreators["Velocity"] = [this](entt::entity entity) {
        getRegistry().emplace<Velocity>(entity, 0.0f, 0.0f);
    };
    
    componentCreators["Sprite"] = [this](entt::entity entity) {
        getRegistry().emplace<Sprite>(entity);
    };
    
    componentCreators["Collider"] = [this](entt::entity entity) {
        getRegistry().emplace<Collider>(entity);
    };
    
    componentCreators["Tag"] = [this](entt::entity entity) {
        getRegistry().emplace<Tag>(entity, "New Entity");
    };
    
    componentCreators["PlayerControl"] = [this](entt::entity entity) {
        getRegistry().emplace<PlayerControl>(entity);
    };

    componentCreators["Script"] = [this](entt::entity entity) {
        getRegistry().emplace<ScriptComponent>(entity);
    };
}

Editor::~Editor() {
}

bool Editor::initialize() {
    // 设置ImGui上下文
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO();
    io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
    io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;

    renderer = engine->getRenderer(); // 在这里获取渲染器

    // 检查渲染器是否有效
    if (!renderer) {
        std::cerr << "Renderer is null in Editor::initialize()!" << std::endl;
        return false;
    }

    // 设置ImGui样式
    ImGui::StyleColorsDark();
    
    // 初始化SDL2后端
    if (!ImGui_ImplSDL2_InitForSDLRenderer(engine->getWindow(), renderer)) {
        return false;
    }
    
    if (!ImGui_ImplSDLRenderer2_Init(renderer)) {
        return false;
    }
    
    return true;
}

void Editor::processInput() {
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        if (event.type == SDL_QUIT) {
            setQuit();
        }
        ImGui_ImplSDL2_ProcessEvent(&event);
    }
}

void Editor::update(float deltaTime) {
    // 开始ImGui帧
    ImGui_ImplSDLRenderer2_NewFrame();
    ImGui_ImplSDL2_NewFrame();
    ImGui::NewFrame();
    
    // 创建停靠空间
    ImGui::DockSpaceOverViewport(0);
    
    // 渲染主菜单
    renderMainMenu();
    
    // 渲染各个窗口
    if (showEntityList) renderEntityList();
    if (showInspector) renderInspector();
    if (showSceneView) renderSceneView();
    if (showResourceView) renderResourceView();
    if (showStats) renderStats();
    if (showDemoWindow) ImGui::ShowDemoWindow(&showDemoWindow);

    renderCreateEntityPopup();
    renderAddComponentPopup();
}

void Editor::render() {
    ImGui::Render();
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderClear(renderer);
    ImGui_ImplSDLRenderer2_RenderDrawData(ImGui::GetDrawData(), renderer);
    SDL_RenderPresent(renderer);
}

void Editor::shutdown() {
    ImGui_ImplSDLRenderer2_Shutdown();
    ImGui_ImplSDL2_Shutdown();
    ImGui::DestroyContext();
}

void Editor::renderMainMenu() {
    if (ImGui::BeginMainMenuBar()) {
        if (ImGui::BeginMenu("File")) {
            if (ImGui::MenuItem("New Scene")) {
                createEmptyScene();
            }
            if (ImGui::MenuItem("Save Scene")) {
                // 保存场景逻辑
            }
            if (ImGui::MenuItem("Load Scene")) {
                // 加载场景逻辑
            }
            ImGui::Separator();
            if (ImGui::MenuItem("Exit")) {
                engine->shutdown();
            }
            ImGui::EndMenu();
        }
        
        if (ImGui::BeginMenu("Edit")) {
            if (ImGui::MenuItem("Create Entity")) {
                showCreateEntityPopup = true;
            }
            ImGui::EndMenu();
        }
        
        if (ImGui::BeginMenu("View")) {
            ImGui::MenuItem("Entity List", NULL, &showEntityList);
            ImGui::MenuItem("Inspector", NULL, &showInspector);
            ImGui::MenuItem("Scene View", NULL, &showSceneView);
            ImGui::MenuItem("Resource View", NULL, &showResourceView);
            ImGui::MenuItem("Stats", NULL, &showStats);
            ImGui::MenuItem("ImGui Demo", NULL, &showDemoWindow);
            ImGui::EndMenu();
        }
        
        // 编辑器模式切换
        ImGui::SameLine(ImGui::GetWindowWidth() - 120);
        if (ImGui::Button(editorMode ? "Play" : "Stop")) {
            editorMode = !editorMode;
            engine->setEngineMode(editorMode ? EngineMode::EditorEngineMode : EngineMode::GameEngineMode);
        }
        
        ImGui::EndMainMenuBar();
    }
}

void Editor::renderEntityList() {
    ImGui::Begin("Entity List", &showEntityList);
    
    // 实体列表
    auto view = getRegistry().view<Tag>();
    for (auto entity : view) {
        const auto& tag = view.get<Tag>(entity);
        bool isSelected = (selectedEntity == entity);
        
        if (ImGui::Selectable(tag.name.c_str(), isSelected)) {
            selectedEntity = entity;
        }
        
        // 右键菜单
        if (ImGui::BeginPopupContextItem()) {
            if (ImGui::MenuItem("Delete")) {
                handleEntityDeletion(entity);
                if (selectedEntity == entity) {
                    selectedEntity = entt::null;
                }
                ImGui::CloseCurrentPopup();
            }
            ImGui::EndPopup();
        }
    }
    
    // 添加实体按钮
    if (ImGui::Button("+ Create Entity")) {
        showCreateEntityPopup = true;
    }
    
    ImGui::End();
}

void Editor::renderCreateEntityPopup() {
    // 首先检查是否需要打开弹出窗口
    if (showCreateEntityPopup) {
        ImGui::OpenPopup("Create Entity");
        showCreateEntityPopup = false; // 重置标志，避免重复打开
    }
    
    // 设置弹出窗口的大小
    ImGui::SetNextWindowSize(ImVec2(400, 200), ImGuiCond_FirstUseEver);
    
    // 开始模态弹出窗口
    if (ImGui::BeginPopupModal("Create Entity", NULL, ImGuiWindowFlags_AlwaysAutoResize)) {
        static char entityName[128] = "New Entity";
        
        ImGui::Text("Create a new entity:");
        ImGui::Separator();
        
        ImGui::InputText("Name", entityName, IM_ARRAYSIZE(entityName));
        
        ImGui::Spacing();
        ImGui::Separator();
        ImGui::Spacing();
        
        // 按钮布局
        if (ImGui::Button("Create", ImVec2(120, 0))) {
            createEntity();
            if (getRegistry().all_of<Tag>(selectedEntity)) {
                auto& tag = getRegistry().get<Tag>(selectedEntity);
                tag.name = entityName;
            }
            // 重置输入框
            strcpy(entityName, "New Entity");
            ImGui::CloseCurrentPopup();
        }
        
        ImGui::SameLine();
        if (ImGui::Button("Cancel", ImVec2(120, 0))) {
            // 重置输入框
            strcpy(entityName, "New Entity");
            ImGui::CloseCurrentPopup();
        }
        
        ImGui::EndPopup();
    }
}

void Editor::renderAddComponentPopup() {
    // 首先检查是否需要打开弹出窗口
    if (showAddComponentPopup) {
        ImGui::OpenPopup("Add Component");
        showAddComponentPopup = false; // 重置标志，避免重复打开
    }
    
    // 设置弹出窗口的大小
    ImGui::SetNextWindowSize(ImVec2(300, 400), ImGuiCond_FirstUseEver);
    
    // 开始模态弹出窗口
    if (ImGui::BeginPopupModal("Add Component", NULL, ImGuiWindowFlags_AlwaysAutoResize)) {
        ImGui::Text("Select component type to add:");
        ImGui::Separator();
        
        // 列出所有可用的组件类型
        for (const auto& [name, creator] : componentCreators) {
            // 检查实体是否已经有这个组件
            bool hasComponent = false;
            if (name == "Position") hasComponent = getRegistry().all_of<Position>(selectedEntity);
            else if (name == "Velocity") hasComponent = getRegistry().all_of<Velocity>(selectedEntity);
            else if (name == "Sprite") hasComponent = getRegistry().all_of<Sprite>(selectedEntity);
            else if (name == "Collider") hasComponent = getRegistry().all_of<Collider>(selectedEntity);
            else if (name == "Tag") hasComponent = getRegistry().all_of<Tag>(selectedEntity);
            else if (name == "PlayerControl") hasComponent = getRegistry().all_of<PlayerControl>(selectedEntity);
            else if (name == "Script") hasComponent = getRegistry().all_of<ScriptComponent>(selectedEntity);

            // 如果实体还没有这个组件，显示添加按钮
            if (!hasComponent) {
                if (ImGui::Button(name.c_str(), ImVec2(-1, 0))) {
                    addComponentToEntity(selectedEntity, name);
                    ImGui::CloseCurrentPopup();
                }
                ImGui::Spacing();
            }
        }
        
        ImGui::Separator();
        
        if (ImGui::Button("Cancel", ImVec2(-1, 0))) {
            ImGui::CloseCurrentPopup();
        }
        
        ImGui::EndPopup();
    }
}

void Editor::renderInspector() {
    ImGui::Begin("Inspector", &showInspector);
    
    if (selectedEntity != entt::null && getRegistry().valid(selectedEntity)) {
        // 显示和编辑标签组件
        if (getRegistry().all_of<Tag>(selectedEntity)) {
            auto& tag = getRegistry().get<Tag>(selectedEntity);
            char nameBuffer[256];
            strcpy(nameBuffer, tag.name.c_str());
            
            if (ImGui::InputText("Name", nameBuffer, sizeof(nameBuffer))) {
                tag.name = std::string(nameBuffer);
            }
        } else {
            if (ImGui::Button("Add Tag Component")) {
                getRegistry().emplace<Tag>(selectedEntity, "Entity");
            }
        }
        
        ImGui::Separator();
        
        // 显示和编辑位置组件
        if (getRegistry().all_of<Position>(selectedEntity)) {
            if (ImGui::CollapsingHeader("Position", ImGuiTreeNodeFlags_DefaultOpen)) {
                auto& position = getRegistry().get<Position>(selectedEntity);
                ImGui::DragFloat("X", &position.x, 1.0f);
                ImGui::DragFloat("Y", &position.y, 1.0f);
            }
        }
        
        // 显示和编辑速度组件
        if (getRegistry().all_of<Velocity>(selectedEntity)) {
            if (ImGui::CollapsingHeader("Velocity")) {
                auto& velocity = getRegistry().get<Velocity>(selectedEntity);
                ImGui::DragFloat("dX", &velocity.dx, 0.1f);
                ImGui::DragFloat("dY", &velocity.dy, 0.1f);
            }
        }
        
        // 显示和编辑精灵组件
        if (getRegistry().all_of<Sprite>(selectedEntity)) {
            if (ImGui::CollapsingHeader("Sprite")) {
                auto& sprite = getRegistry().get<Sprite>(selectedEntity);
                ImGui::Text("Texture: %s", sprite.texturePath.c_str());
                ImGui::Checkbox("Visible", &sprite.visible);
                
                // 纹理选择器
                if (ImGui::Button("Change Texture")) {
                    // 打开纹理选择对话框
                }
            }
        }

        // 显示和编辑脚本组件
        if (getRegistry().all_of<ScriptComponent>(selectedEntity)) {
            auto& scriptComp = getRegistry().get<ScriptComponent>(selectedEntity);
            if (ImGui::CollapsingHeader("Script", ImGuiTreeNodeFlags_DefaultOpen)) {
                ImGui::Text("Script: %s", scriptComp.scriptName.c_str());
                
                // 渲染属性编辑器
                renderPropertyEditor(scriptComp.scriptName, scriptComp);
                
                if (ImGui::Button("Remove Script")) {
                    getRegistry().remove<ScriptComponent>(selectedEntity);
                }
            }
        }
        
        // 添加组件按钮
        ImGui::Separator();
        if (ImGui::Button("Add Component")) {
            showAddComponentPopup = true;
        }
    } else {
        ImGui::Text("No entity selected");
    }
    
    ImGui::End();
}

void Editor::createEmptyScene() {
    getRegistry().clear();
    selectedEntity = entt::null;
    std::cout << "Created empty scene" << std::endl;
}

void Editor::createEntity() {
    selectedEntity = getRegistry().create();
    getRegistry().emplace<Tag>(selectedEntity, "New Entity");
    getRegistry().emplace<Position>(selectedEntity, 0.0f, 0.0f);
    std::cout << "Created new entity: " << static_cast<uint32_t>(selectedEntity) << std::endl;
}

void Editor::addComponentToEntity(entt::entity entity, const std::string& componentType) {
    auto it = componentCreators.find(componentType);
    if (it != componentCreators.end()) {
        it->second(entity);
        std::cout << "Added " << componentType << " component to entity " 
                  << static_cast<uint32_t>(entity) << std::endl;
    }
}

void Editor::renderSceneView() {
    ImGui::Begin("Scene View", &showSceneView);
    
    // 获取视图区域和位置
    isSceneViewHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows);
    sceneViewPos = ImGui::GetCursorScreenPos();
    sceneViewSize = ImGui::GetContentRegionAvail();
    
    // 创建一个子区域作为渲染目标
    ImGui::BeginChild("SceneRender", ImVec2(0, 0), false, 
                     ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar);
    
    // 绘制背景（网格或纯色）
    ImDrawList* drawList = ImGui::GetWindowDrawList();
    drawList->AddRectFilled(sceneViewPos, 
                           ImVec2(sceneViewPos.x + sceneViewSize.x, 
                                 sceneViewPos.y + sceneViewSize.y), 
                           IM_COL32(50, 50, 50, 255));
    
    // 绘制网格
    drawGrid(drawList, sceneViewPos, sceneViewSize, sceneZoom, scenePan);
    
    // 渲染场景中的实体
    auto view = getRegistry().view<Position, Sprite>();
    for (auto entity : view) {
        const auto& position = view.get<Position>(entity);
        const auto& sprite = view.get<Sprite>(entity);
        
        if (sprite.visible && sprite.texture) {
            // 计算屏幕坐标（考虑缩放和平移）
            ImVec2 screenPos = worldToScreen(position.x, position.y);
            ImVec2 spriteSize(sprite.dstRect.w * sceneZoom, sprite.dstRect.h * sceneZoom);
            
            // 绘制精灵
            ImGui::SetCursorScreenPos(screenPos);
            ImGui::Image((void*)(intptr_t)sprite.texture, 
                        spriteSize, 
                        ImVec2(0, 0), ImVec2(1, 1));
            
            // 如果实体被选中，绘制选择框
            if (entity == selectedEntity) {
                drawList->AddRect(screenPos, 
                                 ImVec2(screenPos.x + spriteSize.x, 
                                       screenPos.y + spriteSize.y), 
                                 IM_COL32(255, 255, 0, 255), 0, 0, 2.0f);
            }
        }
    }
    
    // 处理输入
    handleSceneViewInput();
    
    ImGui::EndChild();
    ImGui::End();
}

// 坐标变换函数
ImVec2 Editor::worldToScreen(float worldX, float worldY) {
    return ImVec2(
        (worldX - scenePan.x) * sceneZoom + sceneViewPos.x,
        (worldY - scenePan.y) * sceneZoom + sceneViewPos.y
    );
}

ImVec2 Editor::screenToWorld(float screenX, float screenY) {
    return ImVec2(
        (screenX - sceneViewPos.x) / sceneZoom + scenePan.x,
        (screenY - sceneViewPos.y) / sceneZoom + scenePan.y
    );
}

// 场景视图的网格绘制
void Editor::drawGrid(ImDrawList* drawList, ImVec2 windowPos, ImVec2 windowSize, float zoom, ImVec2 pan) {
    const float gridSize = 50.0f; // 网格大小（世界单位）
    const ImU32 gridColor = IM_COL32(100, 100, 100, 100);
    
    // 计算可见的网格范围
    float startX = std::floor(pan.x / gridSize) * gridSize;
    float startY = std::floor(pan.y / gridSize) * gridSize;
    float endX = startX + windowSize.x / zoom + gridSize;
    float endY = startY + windowSize.y / zoom + gridSize;
    
    // 绘制垂直线
    for (float x = startX; x < endX; x += gridSize) {
        ImVec2 start = worldToScreen(x, startY);
        ImVec2 end = worldToScreen(x, endY);
        drawList->AddLine(start, end, gridColor);
    }
    
    // 绘制水平线
    for (float y = startY; y < endY; y += gridSize) {
        ImVec2 start = worldToScreen(startX, y);
        ImVec2 end = worldToScreen(endX, y);
        drawList->AddLine(start, end, gridColor);
    }
}

void Editor::handleSceneViewInput() {
    if (isSceneViewHovered) {
        // 缩放控制
        float zoomFactor = ImGui::GetIO().MouseWheel * 0.1f;
        if (zoomFactor != 0.0f) {
            // 以鼠标位置为中心进行缩放
            ImVec2 mousePos = ImGui::GetMousePos();
            ImVec2 worldPosBefore = screenToWorld(mousePos.x, mousePos.y);
            
            sceneZoom += zoomFactor;
            sceneZoom = std::max(0.1f, std::min(5.0f, sceneZoom)); // 限制缩放范围
            
            ImVec2 worldPosAfter = screenToWorld(mousePos.x, mousePos.y);
            scenePan.x += (worldPosAfter.x - worldPosBefore.x);
            scenePan.y += (worldPosAfter.y - worldPosBefore.y);
        }
        
        // 平移控制（右键拖拽）
        if (ImGui::IsMouseDragging(ImGuiMouseButton_Right)) {
            scenePan.x -= ImGui::GetIO().MouseDelta.x / sceneZoom;
            scenePan.y -= ImGui::GetIO().MouseDelta.y / sceneZoom;
        }
        
        // 实体选择（左键点击）
        if (ImGui::IsMouseClicked(ImGuiMouseButton_Left)) {
            ImVec2 mousePos = ImGui::GetMousePos();
            ImVec2 worldPos = screenToWorld(mousePos.x, mousePos.y);
            
            // 检查点击了哪个实体
            selectedEntity = findEntityAtPosition(worldPos.x, worldPos.y);
        }
        
        // 实体移动（左键拖拽已选中的实体）
        if (ImGui::IsMouseDragging(ImGuiMouseButton_Left) && selectedEntity != entt::null) {
            ImVec2 mouseDelta = ImGui::GetIO().MouseDelta;
            if (getRegistry().all_of<Position>(selectedEntity)) {
                auto& position = getRegistry().get<Position>(selectedEntity);
                position.x += mouseDelta.x / sceneZoom;
                position.y += mouseDelta.y / sceneZoom;
            }
        }
    }
}

// 实体查找
entt::entity Editor::findEntityAtPosition(float x, float y) {
    auto view = getRegistry().view<Position, Sprite>();
    for (auto entity : view) {
        const auto& position = view.get<Position>(entity);
        const auto& sprite = view.get<Sprite>(entity);
        
        if (sprite.visible) {
            // 检查点是否在实体的矩形内
            if (x >= position.x && x <= position.x + sprite.dstRect.w &&
                y >= position.y && y <= position.y + sprite.dstRect.h) {
                return entity;
            }
        }
    }
    return entt::null; // 没有找到实体
}

void Editor::renderResourceView() {
    ImGui::Begin("Resource View", &showResourceView);
    
    ImGui::InputText("Asset Path", assetPathBuffer, sizeof(assetPathBuffer));
    
    if (ImGui::Button("Load Texture")) {
        // 加载纹理逻辑
    }
    
    // 显示已加载的纹理
    ImGui::Separator();
    ImGui::Text("Loaded Textures:");
    
    // 这里需要访问ResourceManager的纹理列表
    // 为了简化，我们假设有一个获取纹理列表的方法
    
    ImGui::End();
}

void Editor::renderStats() {
    ImGui::Begin("Stats", &showStats);
    
    ImGui::Text("FPS: %.1f", ImGui::GetIO().Framerate);
    ImGui::Text("Frame Time: %.3f ms", 1000.0f / ImGui::GetIO().Framerate);
    //ImGui::Text("Entities: %zu", getRegistry().size());
    
    // ImGui::Separator();
    // ImGui::Text("Components:");
    // ImGui::Text("  Position: %zu", getRegistry().size<Position>());
    // ImGui::Text("  Velocity: %zu", getRegistry().size<Velocity>());
    // ImGui::Text("  Sprite: %zu", getRegistry().size<Sprite>());
    // ImGui::Text("  Collider: %zu", getRegistry().size<Collider>());
    
    ImGui::End();
}

void Editor::handleEntityDeletion(entt::entity entity) {
    engine->destroyEntity(entity);
}

void Editor::renderPropertyEditor(const std::string& scriptName, ScriptComponent& scriptComp) {
    // 获取脚本的属性描述符
    auto properties = engine->getScriptManager().GetScriptProperties(scriptName);
    
    for (const auto& prop : properties) {
        // 获取当前属性值（如果没有则使用默认值）
        PropertyValue currentValue = prop.defaultValue;
        if (scriptComp.properties.find(prop.name) != scriptComp.properties.end()) {
            currentValue = scriptComp.properties[prop.name];
        }
        
        // 渲染属性字段
        ImGui::PushID(prop.name.c_str());
        renderPropertyField(prop, currentValue);
        ImGui::PopID();
        
        // 更新属性值
        scriptComp.properties[prop.name] = currentValue;
        
        // 如果脚本实例存在，也更新实例的属性
        if (scriptComp.instance) {
            scriptComp.instance->SetPropertyValue(prop.name, currentValue);
        }
    }
}

void Editor::renderPropertyField(const PropertyDescriptor& prop, PropertyValue& value) {
    ImGui::Text("%s:", prop.displayName.c_str());
    if (!prop.tooltip.empty()) {
        ImGui::SameLine();
        ImGui::TextDisabled("(?)");
        if (ImGui::IsItemHovered()) {
            ImGui::SetTooltip("%s", prop.tooltip.c_str());
        }
    }
    
    ImGui::Indent();
    
    // 根据属性类型渲染不同的UI控件
    switch (prop.type) {
        case PropertyType::Integer: {
            int intValue = std::get<int>(value);
            if (ImGui::DragInt("##value", &intValue, 1.0f, 
                              std::get<int>(prop.minValue), 
                              std::get<int>(prop.maxValue))) {
                value = intValue;
            }
            break;
        }
        case PropertyType::Float: {
            float floatValue = std::get<float>(value);
            if (ImGui::DragFloat("##value", &floatValue, 0.1f, 
                                std::get<float>(prop.minValue), 
                                std::get<float>(prop.maxValue))) {
                value = floatValue;
            }
            break;
        }
        case PropertyType::Boolean: {
            bool boolValue = std::get<bool>(value);
            if (ImGui::Checkbox("##value", &boolValue)) {
                value = boolValue;
            }
            break;
        }
        case PropertyType::String: {
            std::string stringValue = std::get<std::string>(value);
            char buffer[256];
            strncpy(buffer, stringValue.c_str(), sizeof(buffer));
            if (ImGui::InputText("##value", buffer, sizeof(buffer))) {
                value = std::string(buffer);
            }
            break;
        }
        // 可以添加更多类型的支持
        default:
            ImGui::Text("Unsupported property type");
            break;
    }
    
    ImGui::Unindent();
}

entt::registry& Editor::getRegistry()
{
    return engine->getRegistry();
}